package com.p.lib.retrofit;

import com.heartware.sh.commonlib.BuildConfig;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/5/31 0031.
 */

public class ServiceFactory {

    public final static int CONNECT_TIMEOUT =30;
    public final static int READ_TIMEOUT=100;
    public final static int WRITE_TIMEOUT=60;


    public static <T> T createService(String baseUrl, Class<T> cls){

        OkHttpClient httpClient = new OkHttpClient();

        if (BuildConfig.DEBUG) { //网络请求日志开关, debug模式开启,
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient = new OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                    .writeTimeout(WRITE_TIMEOUT,TimeUnit.SECONDS)//设置写的超时时间
                    .connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)//设置连接超时时间
//                    .sslSocketFactory(sslSocketFactory, trustManager) //TODO 发送HTTPS请求需要添加ssl
                    .build();
        }else{

            httpClient = new OkHttpClient.Builder()
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                    .writeTimeout(WRITE_TIMEOUT,TimeUnit.SECONDS)//设置写的超时时间
                    .connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)//设置连接超时时间
//                  .sslSocketFactory(sslSocketFactory, trustManager) //TODO 发送HTTPS请求需要添加ssl
                    .build();

        }


        Retrofit adapter = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        return adapter.create(cls);

    }

}
